<template>
  <!--电量平衡分析-->
  <d2-container>
  <section class="vue-wrap2">
    <el-row style="padding:0px 20px 6px; background: white;">
      <el-col :span="24" style="margin-top: 15px">
        <el-col :span="10">
         <el-row>
            <el-col :span="6">
              <span style="height: 28px;display: block;line-height: 28px;">计量器具信息:</span>
            </el-col>
            <el-col :span="18">
              <el-input placeholder="请选择计量器"
                class="filter-item"
                style="width:280px;"
                size="mini"
                @click.native="inputParentMeterCodeName()"
                v-model="dataForm.meterCodeName">
              </el-input>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <span style="font-size: 14px;margin-right: 5px">选择时间 :</span>
          <label name="按日" class="label_time_a" v-bind:class="{ active: timeType==='1', 'checked': timeType==='1' }"
                 v-on:click="changeTimeType('1')">按日</label>
          <label name="按月" class="label_time_b" v-bind:class="{ active: timeType==='2', 'checked': timeType==='2' }"
                 v-on:click="changeTimeType('2')">按月</label>
          <label style="margin-left: 30px;">
          <span class="search-input" v-show="timeType == 1">
            <el-date-picker
              type="date"
              size="mini"
              v-model="statSearchDate"
              :picker-options="pickerOptions1"
              placeholder="选择日期"
            ></el-date-picker>
          </span>
          <span class="search-input" v-show="timeType == 2">
            <el-date-picker
              type="month"
              size="medium"
              format="yyyy年MM月"
              v-model="statSearchMonth"
              :picker-options="pickerOptions1"
              placeholder="选择月份"
            ></el-date-picker>
          </span>
          </label>
        </el-col>

        <el-col :span="2" style="text-align: right;">
          <el-button @click="getList(true)" size="mini" type="info"
                     style="width: 80px;border-radius: 0;background: #4d87df;
                        border: 1px solid #4d87df;border-radius: 5px">查询
          </el-button>
        </el-col>
      </el-col>
      <!-- <el-col :span="24" style="margin-top: 15px">
        <div class="clearfloat" style="width:100%;height:auto;overflow:hidden">
          <div style="font-size: 14px;margin-top:10px;">选择对象 :</div>
          <div v-show="objlist.length>0" style="margin-left: 80px;margin-top: -25px;width: 90%;word-wrap:break-word; overflow:hidden;">
            <el-radio-group v-model="selectObj" text-color="#333333" fill="#83acf9"
                            style="font-size: 14px;">
              <template v-for="(item,index) in objlist">
                <el-radio-button :label="item.tree_id" :key="index" style="display: none" :name="item.info.name"
                                 :disabled="item.info.monitor ===0" @change.native="changeObjvalue(item)"
                                 border>
                </el-radio-button>
                <label :name="item.tree_id" :key="item.tree_id" class="label_obj" :for="item.info.name" :disabled="item.info.monitor ===0"
                       v-bind:class="{ active: selectObj===item.tree_id, 'checked': selectObj===item.tree_id }"
                       v-on:click="changeObjvalue(item)">{{item.info.name}}</label>
              </template>
            </el-radio-group>
          </div>
        </div>
      </el-col> -->
    </el-row>
    <el-row style="padding:20px 0px 26px 20px;background: white;">
      <el-col :span="24" class="monitor-d">
        <!--<div style="border: 1px dashed #DADADA;"></div>-->
        <div class="power-statistics" style="border-top: 1px dashed #DADADA;"  v-loading="dayEchartData === '2'" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
          <div class="chart-head clearfloat">
            <span class="tit">电量统计</span>
          </div>
          <!--<div class="statistics-d">-->
            <!--<div class="note" v-show="dayEchartData === '0'" style="width: 100%">-->
              <!--<img src="../../assets/img/noechart.png">-->
              <!--<p>暂无相关数据</p>-->
            <!--</div>-->
            <!--<div id="statEchart1" style="width: 100%">-->
            <!--</div>-->
          <!--</div>-->

          <div class="statistics-d" v-show="timeType == 1">
            <div id="statEchart1" v-show="dayEchartData.length > 0">
            </div>
            <div class="note" v-show="dayEchartData.length == 0">
              <img src="../../assets/img/noechart.png">
              <p>暂无相关数据</p>
            </div>
          </div>
          <div class="statistics-d" v-show="timeType == 2">
            <div id="statEchart2">
            </div>
            <!-- <div class="note" v-show="monthEchartData.length == 0">
              <img src="../../assets/img/noechart.png">
              <p>暂无相关数据</p>
            </div> -->
          </div>

        </div>
      </el-col>
    </el-row>
    <el-row style="padding:20px 20px 26px; background: white;">
      <el-col :span="24">
        <div class="vue-body">
          <div class="chart-head clearfloat">
            <span class="tit">电费信息</span>
          </div>

          <el-table :data="query.list.slice((query.page_no-1)*query.page_size,query.page_no*query.page_size)" stripe class="chart-head" tooltip-effect="dark" style="width: 100%;
       " border>
            <el-table-column prop="calculateDate" label="时间" min-width="120" align="center" :formatter="showDisplayTimeName">
            </el-table-column>
            <el-table-column prop="val" label="电量（kWh）" min-width="120" align="center">
              <template slot-scope="scope">
                {{(scope.row.val).toFixed(1)}}
              </template>
            </el-table-column>
            <el-table-column prop="money" label="电费（元）" min-width="120" align="center">
              <template slot-scope="scope">
                {{(scope.row.money).toFixed(2)}}
              </template>
            </el-table-column>
          </el-table>
          <template>
            <pagintation :total="query.total" :props_page_sizes="query.page_size" @changeCurrent="changeVal" @changeSize="changeSize"></pagintation>
          </template>
          <!--<dialog></dialog>-->
        </div>
      </el-col>
    </el-row>
    <el-dialog title="选择计量器" :visible.sync="showTree">
      <el-tree
        :style="'height:'+(containerHeight-100)+'px'"
        ref="buildTree"
        highlight-current
        node-key="id"
        :data="treeDataList"
        :expand-on-click-node="false"
        :props="menuListTreeProps"
        @node-click="selectBuild"
        default-expand-all
      >
        <span class="custom-tree-node"  slot-scope="{ node, data }">
          <span :dataType="data.type">
              <!-- <i class="el-icon-setting"  v-if="data.type=='b'"></i> -->
              <i class="el-icon-star-off"  v-if="data.type=='d'"></i>
              {{ node.label }}
          </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTree = false">取 消</el-button>
      </div>
    </el-dialog>
  </section>
  </d2-container>
</template>

<script>
  import * as Util from "@/utils";
  import Config from "@/utils/config"
  import commondef from '@/utils/common'
  import pagintation from '@/components/pagintation/index.vue'
  //  import cityList from '../../../api/vueCity'
  import * as echarts from 'echarts'

  export default {
    data () {
      return {
        firstDevice:[],
        statSearch:1,
        showTree:false,
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
        dataForm:{
          meterCodeName:'',
          meterCode:'',
        },
        treeDataList:[],
        customer_id: this.$store.state.customer_id,
        dayEchartData: [],
        monthEchartData:[],
        objlist: [],
        selobj: '',
        powBalance: '2',
        balancStander: '',
        balancStanderName: '下',
        selectObj: '',
        objName: '',
        timeType: '1',
        setUp: false,
        statSearchDate: new Date(new Date().getTime()),
        statSearchMonth: new Date(),
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() > (new Date().getTime())
          }
        },
        menuTree: {
          defaultProps: {
            children: 'children',
            label: 'name'
          },
          data: []
        },
        customerName: this.$store.state.customer_domain_name,
        customer_id: this.$store.state.customer_id,
        show: 'tab',
        query: {
          page_no: 1,
          page_size: 15,
          total: 0,
          list: []
        },
        roleOptions: [],
        editForm: {
          id: '',
          data: {
            customer_domain_name: '',
            role_name: '',
            role_id: '',
            info: {
              home: []
            }
          },
          show: false,
          status: false,
          title: '',
          rules: {
            role_name: [
              {required: true, message: '请输入⻆⾊名称', trigger: 'blur'},
              {max: 30, message: '不能超过 30 个字符', trigger: 'blur'}
            ]
          }
        },
        dayOptin: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        monthOption: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
        optionfad: {
          grid: {
            left: 30,
            top: 40,
            right: 50,
            bottom: 40
          },
          color: ['#708DE5', '#2BD597', '#F5A623'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (val, n) {
              var returnStr = '<div style=\'text-align:left;\'>' +
                '时间：' + val[0].name + '<br/>'
              for (var i in val) {
                returnStr = returnStr +
                  '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                  val[i].seriesName + '：' + val[i].value + (val[i].seriesName === '纯电量费用' ? ' 元' : ' 元/kWh') +
                  '<br/>'
              }
              returnStr = returnStr + '</div>'
              return returnStr
            }
          },
          legend: {
            x: 'right',
            padding: [15, 50, ,],
            itemWidth: 10,
            itemHeight: 10,
            data: [{
              name: '有功电量',
              icon: 'circle'
            }, {
              name: '下属线路有功电量',
              icon: 'circle'
            }, {
              name: '不平衡度',
              icon: 'circle'
            }],
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: true,
              data: []
            },
            {
              type: 'category',
              boundaryGap: true,
              show: false,
              data: []
            }
          ],
          yAxis: [
            {
              type: 'value',
              scale: true,
              splitNumber: 6,
              name: '单位  kWh',
              boundaryGap: [0.2, 0.2],
              splitLine:{
                show : true
              },
              axisLabel: {
                formatter: function (a) {
                  return a >= 1000
                    ? echarts.format.addCommas(a / 1000) + 'k'
                    : a
                }
              }
            },
            {
              type: 'value',
              scale: true,
              splitNumber: 6,
              axisLabel: {
                formatter: function (a) {
                  return (a) + '%'
                }
              },
              boundaryGap: [0.2, 0.2],
              splitLine:{
                show : false
              }
            }
          ],
          series: [
            {
              name: '有功电量',
              type: 'bar',
              barGap: '30%',
              barWidth: '30%',
              barCategoryGap: '70%',
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              },
              data: []
            },
            {
              name: '下属线路有功电量',
              type: 'bar',
              barGap: '30%',
              barWidth: '30%',
              barCategoryGap: '70%',
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              },
              data: []
            },
            {
              name: '不平衡度',
              type: 'line',
              yAxisIndex: 1,
              data: []
            }
          ]
        },
        powerEchart: {
          option: {
            grid: {
              left: 40,
              top: 40,
              right: 20,
              bottom: 40
            },
            color: ['#708DE5', '#2BD597']
          },
          dateOption: {
            legend: {
              top: 10,
              right: 20,
              itemWidth: 10,
              itemHeight: 10,
              data: [{
                name:'上日',
                icon:'circle'
              }, {
                name:'当日',
                icon:'circle'
              }]
            },
            xAxis: {
              type: 'category',
              axisTick: { show: false },
              data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function(val, n) {
                var returnStr = "<div style='text-align:left;'>" +
                  "时间：" + val[0].name + ":00<br/>";
                for (var i in val) {
                  returnStr = returnStr +
                    "<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:" + val[i].color + "'></span>" +
                    val[i].seriesName + "：" + parseInt(val[i].value) + " kWh" +
                    "<br/>"
                }
                returnStr = returnStr + "</div>";
                return returnStr;
              }
            }
          },
          monthOption: {
            legend: {
              top: 10,
              right: 20,
              itemWidth: 10,
              itemHeight: 10,
              data: [{
                name:'上月',
                icon:'circle'
              }, {
                name:'当月',
                icon:'circle'
              }]
            },
            xAxis: {
              type: 'category',
              data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function(val, n) {
                var returnStr = "<div style='text-align:left;'>" +
                  "时间：" + val[0].name + "日<br/>";
                for (var i in val) {
                  returnStr = returnStr +
                    "<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:" + val[i].color + "'></span>" +
                    val[i].seriesName + "：" + val[i].value+ " kWh" +
                    "<br/>"
                }
                returnStr = returnStr + "</div>";
                return returnStr;
              }
            }
          }
        }
      }
    },
    mounted () {
      //this.showvalue(1)
      this.getBuildDeviceList();
    },
    components: {
      pagintation
    },
    computed:{
      containerHeight() {
        return Util.getClientHeight() - 243;
      }
    },
    methods: {
      changeData() {
        this.dayEchartData=[]
        // if(!this.$store.state.meterpara){
        // this.dayEchartData = [];
        // return false;
        //}
        var that = this;
        //获取年月
        var year = new Date(that.statSearchMonth).getFullYear();
        var premonth = new Date(that.statSearchMonth).getMonth();

        //请求
        var para = {
          meterCode: this.dataForm.meterCode,
          customerId: this.$util.cookies.get("customer_id")
        }

        //获取日期时间
        var statSearchDate = that.statSearchDate.format('yyyy-MM-dd');
        var statSearchBeginDate = new Date(new Date(that.statSearchDate).getTime() - 24 * 60 * 60 * 1000).format('yyyy-MM-dd');

        para.begin = statSearchBeginDate;
        para.end = statSearchDate;

        this.$http({
          url: this.$http.adornUrl('/eda/datavincent.reportservice.get_energydailyconsumbygroup'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then(res => {
          if (res.code === 0) {
            var data = res.data || [];
            if(data.length>0){
              that.dayEchartData = data[0].daily_data || [];
              that.query.list = data[1].price_data
              this.query.total = data[1].price_data.length
            }
            if (data.length > 0 && data[0].daily_data && data[0].daily_data.length > 0) {
              var options = {};
              //设置数组
              var data1 = data[0] ? data[0].consume_data : [];
              var data2 = data[1] ? data[1].consume_data : [];
              options.series = [{
                name: '上日',
                type: 'bar',
                barGap: '20%',
                barCategoryGap: '40%',
                data: data1,
                itemStyle: {
                  //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                  emphasis: {
                    barBorderRadius: 30,
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(112,141,229, 0.5)'
                  },

                  normal: {
                    //柱形图圆角，初始化效果
                    barBorderRadius:10
                  }
                }
              }, {
                name: '当日',
                type: 'bar',
                barGap: '20%',
                barCategoryGap: '40%',
                data: data2,
                itemStyle: {
                  //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                  emphasis: {
                    barBorderRadius: 30,
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(3,213,151, 0.5)'
                  },

                  normal: {
                    //柱形图圆角，初始化效果
                    barBorderRadius:10
                  }
                }
              }];
              options.yAxis = {
                name: '单位 kWh',
                type: 'value',
                splitNumber: 5
              };
              //设置横坐标
              Object.assign(options, that.powerEchart.option, that.powerEchart.dateOption);

              //初始化图表
              setTimeout(function(){
                let myChart = echarts.init(document.getElementById('statEchart1'));
                myChart.clear();
                //画图
                myChart.setOption(options);
              }, 500);
            }
          }
        })
      },
      getLastDay (year, month) {
        let newYear = year  //  取当前的年份
        let newMonth = month  // 取下一个月的第一天，方便计算（最后一天不固定）
        let newDate = new Date(newYear, newMonth, 1)        //  取当年当月中的第一天
        return new Date(newDate.getTime() - 1000 * 60 * 60 * 24)
      },
      changeMonth() {
        this.monthEchartData=[]
        // if(!this.$store.state.meterpara){
        //   this.monthEchartData = [];
        //   return false;
        // }
        var that = this;
        //获取年月
        var year = this.statSearchMonth.getFullYear();
        var premonth = this.statSearchMonth.getMonth();

        //请求
        // var apiurl = api.urlList.datavincent.reportservice.get_multipled_energydailyconsumebygroup; //月份
        var para = {
          meterCode: this.dataForm.meterCode,
          customerId: this.$util.cookies.get("customer_id")
        }
        //获取月份时间
        var statSearchMonth = that.statSearchMonth.format('yyyy-MM');
        /*      var statSearchBeginMonth = year + "-" + (premonth > 9 ? premonth : "0" + premonth) + "-01";
              var statSearchEndMonth = year + "-" + (premonth + 2 > 9 ? premonth + 2 : "0" + (premonth + 2)) + "-01";
              if (premonth == 0) {
                statSearchBeginMonth = (year - 1) + "-12-01";
              }
              if (premonth == 12) {
                statSearchEndMonth = (year + 1) + "-01-31";
              }else{
                statSearchEndMonth = new Date(new Date(statSearchEndMonth).getTime() - 24 * 60 * 60 * 1000).format("yyyy-MM-dd")
              }*/
        let startmonth = this.statSearchMonth.getMonth()
        let startyear = this.statSearchMonth.getFullYear()
        if(startmonth===1){
          startyear = startyear-1
          startmonth= 12
        }else{
          startmonth=startmonth-1
        }

        var statSearchBeginMonth = new Date(startyear, startmonth, 1).format('yyyy-MM-dd')
        var statSearchEndMonth = that.getLastDay(this.statSearchMonth.getFullYear(), (this.statSearchMonth.getMonth() + 1)).format('yyyy-MM-dd')

        para.begin = statSearchBeginMonth;
        para.end = statSearchEndMonth;


        that.$http({
          url: that.$http.adornUrl('/eda/datavincent.reportservice.get_multipled_energydailyconsumebygroup'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then(res => {
          if(res.code === 0){
          var data = res.data;
          if (data) {
            that.query.list = data.priceList
            this.query.total = data.priceList.length

            //设置上月这月的数据
            var data1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//上月
            var data2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//本月
            //整理数据
            if(data.last&&data.last.length>0) {
              for (var i in  data.last) {
                var datei = data.last[i].date || '';
                var dayi = datei.substring(datei.length - 2);
                dayi = parseInt(dayi, 10) - 1;
                data1[dayi] = data.last[i].dailySum;
              }
            }
            if(data.cur&&data.cur.length>0) {
              for (var i in  data.cur) {
                var datei = data.cur[i].date || '';
                var dayi = datei.substring(datei.length - 2);
                dayi = parseInt(dayi, 10) - 1;
                data2[dayi] = data.cur[i].dailySum;
              }
            }


            var options = {};
            options.series = [{
              name: '上月',
              type: 'bar',
              barGap: '20%',
              barCategoryGap: '40%',
              data: data1,
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },

                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              }
            }, {
              name: '当月',
              type: 'bar',
              barGap: '20%',
              barCategoryGap: '40%',
              data: data2,
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(3,213,151, 0.5)'
                },

                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              }
            }];
            var maxData = Math.max(...data2);
            var ktrue = false;
            if (maxData > 1000) {
              ktrue = true;
            }
            options.yAxis = {
              name: '单位 kWh',
              type: 'value',
              splitNumber: 5,
              axisLabel: {
                show: true,
                interval: 'auto',
                formatter: function (value, index) {
                  return ktrue ? Math.round(value / 10) * 0.01 + ' k' : value;
                }
              }
            };
            //获取横坐标长度
            var xAxis = that.powerEchart.monthOption.xAxis || {};
            var xAxisData = xAxis.data || [];
            //获取月份对应的日期
            var days1 = new Date(year, premonth, 0);
            if (premonth == 0) {
              days1 = new Date(year - 1, 12, 0);
            }
            days1 = days1.getDate();
            var days2 = new Date(year, premonth + 1, 0);
            days2 = days2.getDate();
            xAxisData = xAxisData.slice(0, days1 > days2 ? days1 : days2);
            // xAxisData = xAxisData.slice(0, data1.length > data2.length ? data1.length : data2.length);
            Object.assign(options, that.powerEchart.option, that.powerEchart.monthOption, {xAxis: [{data: xAxisData}]});
            //初始化图表
            this.monthEchartData = res.data.data.cur.concat(res.data.data.last);
            setTimeout(function () {
              let myChart = echarts.init(document.getElementById('statEchart2'));
              myChart.clear();
              //画图
              myChart.setOption(options);
            }, 300);
          }
        }
      });
      },
      inputParentMeterCodeName(){
        this.showTree = true;
      },
      selectBuild(data){
        //console.log(data);
        //if(data.type=='m'){
        if(data.type=='d'){
          this.dataForm.meterCodeName = data.name;
          this.dataForm.meterCode = data.id;
          this.showTree = false;
        }
      },
      getBuildDeviceList(){
        //查询采集-计量器树
        // this.$http({
        //   url: this.$http.adornUrl("/ecs/ecsmeterinfo/getDeviceTree"),
        //   method: "get",
        //   params: this.$http.adornParams({
        //     "customerId":this.$util.cookies.get('customer_id'),
        //     'projectId': this.$util.cookies.get("cuuren_projectId"),
        //   })
        // }).then(res=>{
        //   if (res && res.data.code == 0) {
        //     this.treeDataList = Util.treeDataTranslate(res.data.data,"id","pid");
        //     //console.log(this.treeDataList);
        //     this.getFirstDevice(this.treeDataList,'m');
        //     if(res.data.data.length>0){
        //       this.$nextTick(()=>{
        //         this.dataForm.meterCodeName = this.firstDevice[0].name
        //         this.dataForm.meterCode= this.firstDevice[0].id
        //         this.changeData()
        //       })
        //     }
        //   }
        // })
        //建筑-计量器树
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/getDeviceTree"),
          method: "get",
          params: this.$http.adornParams({
            "meterType":'010000',
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((res)=>{
          if (res && res.code == 0) {
          this.treeDataList = Util.treeDataTranslate(res.data,"id","pid");
          //   console.log(JSON.stringify(this.treeDataList));
           this.getFirstDevice(this.treeDataList,'d');
          if(res.data.length>0){
            this.$nextTick(()=>{
                this.dataForm.meterCodeName = this.firstDevice[0].name
                this.dataForm.meterCode= this.firstDevice[0].id
                this.changeData()
          })
          }
        }
      })
      },
      changeTimeType (value) {
        this.timeType = value
        this.getList();
      },
      objOnclick (item) {
        var labels = document.getElementById('selectObj').getElementsByTagName('label')
        var radios = document.getElementById('selectObj').getElementsByTagName('input')
        var obj = document.getElementsByName(item.tree_id)
        if (obj[0].className == '') {
          for (var k = 0, l = labels.length; k < l; k++) {
            labels[k].className = ''
            radios[k].checked = false
          }
          obj[0].className = 'checked'
          var obj1 = document.getElementById(item.info.name)
          obj1.checked = true
          this.changeObjvalue(item)
        }
      },
      filterValue (value, row, column) {
        return this.formatObjvalue(row) === value
      },
      changeObjvalue (item) {
        this.selectObj = item.tree_id
        this.objName = item.info.name
        if (this.powBalance === '1') {
          var eddyb = item.info.leave.toUpperCase()
          if (eddyb === '1-10KV') {
            this.balancStander = '±5%'
            this.balancStanderName = '下'
          } else {
            this.balancStander = '±2%'
            this.balancStanderName = '上'
          }
        } else if (this.powBalance === '2')
          var eddyb = item.base_info.base_info.eddyb.split('/')
        if (parseFloat(eddyb[0] / eddyb[1]) <= parseFloat(10.5 / 0.4)) {
          this.balancStander = '±5%'
          this.balancStanderName = '下'
        } else {
          this.balancStander = '±2%'
          this.balancStanderName = '上'
        }
      },
      formatObjvalue (item) {
        var balancStander = ''
        var eddyb = item.pro * 100
        var standar = 0
        if (this.balancStander === '±5%') {
          standar = 5
        } else if (this.balancStander === '±2%') {
          standar = 2
        }
        if (eddyb <= standar && eddyb >= -standar) {
          balancStander = '正常'
        } else {
          balancStander = '超标'
        }
        return balancStander
      },
      showvalue (flag) {
        var para = {
          customer_id: this.customer_id,
          type: this.powBalance
        }
        api.axiosRequest(api.urlList.dist_power.node.get_by_type, para)
          .then(res => {
            if (res.code === commondef.resCode.OK) {
              this.objlist = res.list
              for (let j = 0; j < this.objlist.length; j++) {
                if (this.objlist[j].info.monitor !== 0) {
                  this.selectObj = this.objlist[j].tree_id
                  this.changeObjvalue(this.objlist[j])
                  break
                }
              }
              if(flag){
                this.getList()
              }
            }
          })
      },
      showDisplayName (row, column, cellValue) {
//        console.log(cellValue)
        return '<img src=\"../../assets/img/lower.png\">' + cellValue
      },
      changeVal (val) {
        this.query.page_no = val
//        this.getList()
      },
      changeSize (val) {
        this.query.page_size = val
//        this.getList()
      },
      renderContent: function (createElement, {node, data, store}) {
        return createElement('span', {
          attrs: {
            style: 'display:inline-block; position: relative;width: 100%'
          }
        }, [
          createElement('span', node.label),
          createElement('span', {
            attrs: {
              style: 'position: absolute; right: 100px'
            }
          })
        ])
      },
      getFirstDevice(arr,type) {
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i]
          if (item.children&&item.children.length>0) {
            this.getFirstDevice(item.children, type)
          }else {
            if (item.type === type) {
              this.firstDevice.push(item);
            }
          }
        }
      },
      getList () {
         this.query.page_no =1;
         this.query.list = []
         if(this.timeType==='1'){
           this.changeData();
         }else{
           this.changeMonth();
         }
      },
      monthTimefun (val) {
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(this.statSearchMonth.getFullYear(), this.statSearchMonth.getMonth(), val[0].name).format('yyyy-MM-dd')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName.replace('有功电量', '') + '：' + val[i].value + (val[i].seriesName === '不平衡度' ? ' %' : ' kWh') +
            '<br/>'
        }
        returnStr = returnStr + '</div>'
        return returnStr
      },
      getbar (data) {
        var that = this
        //设置数组
        var data1 = []
        var data2 = []
        var data3 = []
        var dlmin = 0
        var dlmax = 0
        var phmin = 0
        var phmax = 0
        if (data.length > 0) {

          that.dayEchartData = '1'
          var dataAll = data//所有
          var options = {}
          var k = 0
          var xaislength = that.timeType === '1' ? 24 : 32
          for (var i = 0; i < xaislength; i++) {
            if (k < dataAll.length) {
              var day = that.timeType === '1' ? (new Date(dataAll[k].time).format('hh')) : (new Date(dataAll[k].time).format('dd'))
              if (i === (parseInt(day) - (that.timeType === '1' ? 0 : 1))) {
                data1.push(dataAll[k].p_val.toFixed(1))
                data2.push(dataAll[k].ch_val.toFixed(1))
                data3.push((dataAll[k].pro * 100).toFixed(1))
                if(parseFloat(dataAll[k].p_val.toFixed(1))>=dlmax){
                  dlmax = parseFloat(dataAll[k].p_val.toFixed(1))
                }
                if(parseFloat(dataAll[k].ch_val.toFixed(1))>=dlmax){
                  dlmax = parseFloat(dataAll[k].ch_val.toFixed(1))
                }
                if(parseFloat((dataAll[k].pro * 100).toFixed(1)) >= phmax){
                  phmax = parseFloat((dataAll[k].pro * 100).toFixed(1))
                }
                if(parseFloat((dataAll[k].pro * 100).toFixed(1))<=phmin){
                  phmin = parseFloat((dataAll[k].pro * 100).toFixed(1))
                }

                k++
              } else {
                data1.push('')
                data2.push('')
                data3.push('')
              }
            }
          }
        } else {
          return false
        }
        function getLastDay (year, month) {
          let newYear = year  //  取当前的年份
          let newMonth = month  // 取下一个月的第一天，方便计算（最后一天不固定）
          let newDate = new Date(newYear, newMonth, 1)        //  取当年当月中的第一天
          return new Date(newDate.getTime() - 1000 * 60 * 60 * 24)
        }
        //获取横坐标长度
        var monthtooltips = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            var returnStr = '<div style=\'text-align:left;\'>' +
              '时间：' + val[0].name + '日<br/>'
//            for (var i in val) {
            /*//              returnStr = returnStr +
            //                '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            //                val[i].seriesName.replace('有功电量','') + '：' + val[i].value + (val[i].seriesName === '不平衡度' ? ' %' : ' kWh') +
            //                '<br/>'
            //            }
            //            returnStr = returnStr + '</div>'*/
            return that.monthTimefun(val)
          }
        }
        var daytooltips = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            var returnStr = '<div style=\'text-align:left;\'>' +
              '时间：' + val[0].name + ':00<br/>'
            for (var i in val) {
              returnStr = returnStr +
                '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                val[i].seriesName.replace('有功电量', '') + '：' + val[i].value + (val[i].seriesName === '不平衡度' ? ' %' : ' kWh') +
                '<br/>'
            }
            returnStr = returnStr + '</div>'
            return returnStr
          }
        }
        var optionsfand = that.optionfad
        optionsfand.series[0].name = that.objName + '有功电量'
        optionsfand.legend.data[0].name = that.objName + '有功电量'
        optionsfand.tooltip = that.timeType === '1' ? daytooltips : monthtooltips
        var xAxisData = that.timeType === '1' ? that.dayOptin : that.monthOption
        optionsfand.xAxis[0].data = xAxisData.slice(0, that.timeType === '1' ? 24 : parseInt(getLastDay(that.statSearchMonth.getFullYear(), (that.statSearchMonth.getMonth() + 1)).format('dd')))

        var ylen = parseInt(String(parseInt(dlmax)).length)
        optionsfand.yAxis[0].min = 0
        optionsfand.yAxis[0].max = (Math.ceil(dlmax/(3*Math.pow(10,ylen-1))))*3*Math.pow(10,ylen-1)
        var maxNum = Math.abs(phmax)
        var minNum = 0
        if(Math.abs(phmin)>Math.abs(phmax)){
          maxNum = Math.abs(phmin)
        }

        if(phmax<0||phmin>0){
          maxNum = Math.ceil(maxNum/6)*6
          if(phmax<0){
            minNum = -maxNum
            maxNum = 0
          }
        }else{
          maxNum = Math.ceil(maxNum/3)*3
          minNum = -maxNum
        }

        optionsfand.yAxis[1].min = minNum
        optionsfand.yAxis[1].max = maxNum
        optionsfand.series[0].data = data1
        optionsfand.series[1].data = data2
        optionsfand.series[2].data = data3
        setTimeout(function () {
          //画电费电量图
          let myChart2 = echarts.init(document.getElementById('statEchart1'))
          myChart2.clear()
          myChart2.setOption(optionsfand)
        }, 500)
      },
      showDisplayTimeName(row, column, cellValue) {
        return this.timeType==='1'? (new Date(cellValue).format('yyyy-MM-dd  '))+ row.calculateHour+":00:00":cellValue
      }
    },
  }
</script>

<style scoped lang="scss">
  @import "../../assets/scss/_variables";
  .top-but-box.el-col.el-col-2 {
    margin-right: 20px;
  }

  .el-input.el-input--small {
    width: 205px;
  }

  .chart-head {
    margin-top: 10px;
  }

  .clearfloat:after {
    display: block;
    clear: both;
    content: "";
    visibility: hidden;
    height: 0
  }

  .clearfloat {
    zoom: 1
  }

  .power-statistics {
    /*padding: 5px 5px 10px 15px;*/
    height: 290px;
    background: $font-white;
    width: 100%;
  }

  .note {
    padding: 20px;
    text-align: center;
    color: #666;
  }

  .note img {
    width: 140px;
  }

  .statistics-d > div {
    height: 300px;
    width: 100%;
  }

  .label_obj {
    font-family: MicrosoftYaHei;
    display: -moz-inline-block;
    display: inline-block;
    cursor: pointer;
    margin: 0 10px;
    line-height: 30px;
    background: none;
    padding: 1px 10px;
    border-radius: 4px;
    border: 1px solid #fff;
    font-size: 14px;
    color: #666666;
  }

  .label_time_a {
    font-family: MicrosoftYaHei;
    display: -moz-inline-block;
    display: inline-block;
    cursor: pointer;
    line-height: 24px;
    background: none;
    padding: 1px 10px;
    border-radius: 4px 0 0 4px;
    border: 1px solid #E5E5E5;
    font-size: 14px;
    color: #666666;
    margin-left: 18px;
  }

  .label_time_b {
    font-family: MicrosoftYaHei;
    display: -moz-inline-block;
    display: inline-block;
    cursor: pointer;
    line-height: 24px;
    background: none;
    padding: 1px 10px;
    border-radius: 0px 4px 4px 0px;
    border: 1px solid #E5E5E5;
    font-size: 14px;
    color: #666666;
    margin-left: -5px;
  }

  label.checked {
    border: 1px solid #678AF4;
    color: #678AF4;
  }
</style>

